(function () {
    angular.module('feibo.teacher.controller').controller('addTeacherContractGroupCtrl', addTeacherContractGroupCtrl);

    addTeacherContractGroupCtrl.$inject = ['$stateParams', 'TeacherService', 'kvMap', 'CommonService', '$timeout', '$state'];

    function addTeacherContractGroupCtrl($stateParams, TeacherService, kvMap, CommonService, $timeout, $state) {
        var vm = this;
        vm.data = {
            contractId: null,
            groupId: $stateParams.id,
            groupInfo: undefined,
            searchData: {
                user_id: ''
            },
            httpPostData: {
                fb_shift_type_id: '',
            },
            httpGetTeacher: {
                employeeStatus: ''
            },
            // miniTypelist: undefined,
            fb_shift_type_info: '',
            fb_shift_type: {
                id: undefined
            },
            init: function () {
                this.week = CommonService.cloneMapping(kvMap.week, ['vkMap', 'common']);
                this.httpGetTeacher.employeeStatus = [kvMap.employeeStatus.EMPLOYEE].toString();
                return this;
            }
        }.init();
        vm.initData = function () {
            vm.getPackTeacher();
            // vm.fetchClassMiniType();
        };
        /*
         * ***************获取专属合同老师组*********************
         *         ****************************
         */
        vm.getPackTeacher = function () {
            var data = vm.data;
            var queryConfig = {
                funcName: 'getPackTeacher',
                container: data,
                propName: 'groupInfo',
                propChain: ['data'],
                showLoadLayer: false,
                urlPlaceholder: {
                    id: data.groupId
                }
            };
            TeacherService.getPackInfo(queryConfig).then(function (returnedData) {
                vm.data.httpPostData.fb_shift_type_id = returnedData.data.fb_shift_type_id;
                vm.data.fb_shift_type.id = returnedData.data.fb_shift_type_id;
                vm.data.contractId = returnedData.data.buyout_teacher_contract.id;
                if (returnedData.data.fb_shift_type) {
                    var time_solt = returnedData.data.fb_shift_type.shift_time_slot;
                    var time = new TimeQuantum(time_solt);
                    time.init();
                    vm.data.fb_shift_type_info = time.allWeek;
                }
            }).catch(function (error) {
                console.error(error);
            });
        };
        /*
         * ***************获取班型小类*********************
         *         ****************************
         */
        // vm.fetchClassMiniType = function () {
        //     var queryConfig = {
        //         funcName: 'fetchClassMiniType',
        //         container: vm.data,
        //         propName: 'miniTypelist',
        //         propChain: ['data', 'entries'],
        //         showLoadLayer: false
        //     };
        //     TeacherService.fetchClassMiniType(queryConfig).then(function (returnedData) {

        //     }).catch(function (error) {
        //         console.error(error);
        //     });
        // };
        vm.initDrop = function () {
            $timeout(function () {
                // $('#miniType').dropdown();
                console.log(vm.data.fb_shift_type.id);
                $('#miniType').dropdown('set selected', vm.data.fb_shift_type.id.toString());
            });

        };

        //小类下拉chang事件
        vm.selectChangeEvt = function () {
            // 获取小类
            var data = vm.data;
            var queryConfig = {
                container: vm.data,
                propName: 'miniTypeInfo',
                funcName: 'selectChangeEvt',
                propChain: ['data', 'entries'],
                showLoadLayer: false,
                urlPlaceholder: {
                    id: data.fb_shift_type.id
                }
            };

            if(queryConfig.urlPlaceholder.id == 0){
                return;
            }

            TeacherService.getClassMiniType(queryConfig).then(function (returnedData) {
                if ( returnedData.success && returnedData.data.shift_time_slot) {
                    var time_solt = returnedData.data.shift_time_slot;
                    var time = new TimeQuantum(time_solt);
                    time.init();
                    vm.data.fb_shift_type_info = time.allWeek;
                }
            });
        };
        //修改班型小类
        vm.changePackMiniType = function() {
            var putConfig = {
                funcName: 'changePackMiniType',
                successMsg: '更新班型小类成功',
                errorMsg: '更新班型小类失败',
                showLoadLayer: false,
                httpPutData: {
                    fb_shift_type_id: vm.data.fb_shift_type.id,
                },
                urlPlaceholder: {
                    id: vm.data.groupId
                }
            };
            TeacherService.updatePack(putConfig).then(function (resData){
                if (resData.success) {
                    $state.go('teacher-contract-group',{contractId: vm.data.contractId})
                }
            })
        }
/*
         * ***************添加老师处理函数*********************
         *         ****************************
         */
        vm.addTeacher = function () {
            var postConfig = {
                funcName: 'addTeacher',
                successMsg: '添加买断老师成功',
                errorMsg: '添加买断老师失败',
                showLoadLayer: false,
                httpPostData: {
                    fb_shift_type_id: vm.data.fb_shift_type.id,
                    buyout_teacher_pack_id: vm.data.groupId,
                    teacher_id: vm.data.searchData.user_id
                }
            };
            //Object.keys(vm.data.httpPostData).forEach(function (item) {
            //    postConfig.httpPostData[item] = vm.data.httpPostData[item];
            //});
            TeacherService.addBuyTeacher(postConfig).then(function (data) {
                if (data.success) {
                    vm.changePackMiniType();
                }
            })
        };
        vm.searchTeacher = {
            url: ENDPOINTS.teacher.fetchTeachers + '?employeeStatus=4&page_size=10&name={query}',
            container: vm.data.searchData,
            propName: 'user_id',
            propChain: ['data', 'entries'],
            resultsPropsConfig: {
                title: ['user.nickname', 'country'],
                value: ['user_id']
            }
        };


        /*
         * ***************获取班型小类时间段处理函数*********************
         *         ****************************
         */
        function TimeQuantum(data) {
            this.data = data;
            this.allWeek = [];
            this.timeArr = [];
            this.fianelArr = [];
            this.oldTimeArr = [];
            this.init = function () {
                this.getAllWeekArr(this.data);
            };
            /*
             * @Parmas 传入对象
             *
             * return 返回一个包含时间点的属性的数组对象
             * */
            this.getAllWeekArr = function (data) {
                for (var i = 0; i < data.length;) {
                    var obj = {
                        week: undefined,
                        time_slot: []
                    };
                    var index = [];
                    index.push(i);
                    obj.week = data[i].day_of_week;
                    obj.time_slot.push(data[i].time_slot);
                    for (var j = 1; j < data.length; j++) {
                        if (data[i].day_of_week == data[j].day_of_week) {
                            obj.time_slot.push(data[j].time_slot);
                            index.push(j)

                        }
                    }
                    for (var k = 0; k < index.length; k++) {
                        data.splice(0, 1);
                    }
                    obj.time_slot = obj.time_slot.unique();
                    this.allWeek.push(obj);
                }
                ;
                for (var i = 0; i < this.allWeek.length; i++) {
                    this.oldTimeArr = this.allWeek[i].time_slot;
                    this.getfinalArr(this.oldTimeArr);
                    this.allWeek[i].time_slot = this.getFirstAndEnd(this.fianelArr);
                    this.fianelArr = [];
                }
            };
            this.getfinalTimeArr = function (arr1) {
                if (arr1 && arr1.length > 0) {
                    var time_first = this.getTimePart(arr1);
                    this.fianelArr.push(time_first);
                    if (this.oldTimeArr) {
                        var newArr = this.getNewTimeArr(time_first, this.oldTimeArr);
                        this.getfinalTimeArr(newArr);
                    }
                }
            };
            this.getfinalArr = function (arr) {
                this.getfinalTimeArr(arr);
            };
            /*
             *
             *
             * return 返回某星期天中的一个时间段
             * */
            this.getTimePart = function () {
                var arr = this.oldTimeArr;
                var len = arr.length;
                var inTimeArr = [];
                if (arr && len > 1) {
                    inTimeArr.push(arr[0]);
                    for (var i = 0; i < len - 1; i++) {
                        var stm = arr[i].split(':');
                        var ntm = arr[i + 1].split(':');
                        var st = new Date(2000, 1, 1, stm[0], stm[1], stm[2]).getTime();
                        var en = new Date(2000, 1, 1, ntm[0], ntm[1], ntm[2]).getTime();
                        var s = en - st;
                        if (s <= 1800000) {
                            inTimeArr.push(arr[i + 1]);
                        } else {
                            break;
                        }
                    }
                } else if (arr && len == 1) {
                    inTimeArr.push(arr[0])
                } else {
                    return;
                }
                return inTimeArr;
            };
            /*
             * @Parmas1 传入一个时间段数组,@Parmas2传入一个该时间段所在源数组.
             *
             * return 返回一个去掉传入的时间段数组
             * */
            this.getNewTimeArr = function (arr, oldArr) {
                var len = arr.length;
                oldArr.splice(0, len);
                return oldArr;
            };
            /*
             * @Parmas1 数组,可以是两维.
             *
             * return 数组中每个元素数组第一个和最后一个元素
             * */
            this.getFirstAndEnd = function (handle) {
                for (var i = 0, len = handle.length; i < len; i++) {
                    var handleArr = [];
                    var l = handle[i].length;
                    if (l >= 2) {
                        handleArr.push(this.removeSecond(handle[i][0]));
                        handleArr.push(this.initDate(handle[i][handle[i].length - 1]));
                        handle[i] = [];
                        handle[i] = handleArr;

                    } else {
                        handle[i][1] = this.initDate(handle[i][0]);
                        handle[i][0] = this.removeSecond(handle[i][0]);
                    }
                }
                return handle;

            };
            /*
             * @Parmas1 一个字符串 @ "00:30:00".
             *
             * return 时间加上30分钟后的字符串 @ "00:10:00"
             * */
            this.initDate = function (str) {
                var final = [];
                var strArr = str.split(':');
                var st = new Date(2000, 1, 1, strArr[0], strArr[1], strArr[2]).getTime();
                st += 1800000;
                var newDate = new Date(st).toString();
                final = newDate.split(' ');
                return this.removeSecond(final[4]);

            },
                /*
                 * @Parmas1 一个字符串 @ "00:10:00".
                 *
                 * return 去掉最后秒数 @"00:10"
                 * */
                this.removeSecond = function (str) {
                    var m = [];
                    var strs = str.split(':');
                    var s1 = strs[0],
                        s2 = strs[1],
                        moveSeconds = s1 + ":" + s2;

                    m.push(moveSeconds);
                    return m;
                }
        }

        /*
         * @维数组扩展一个区重复数据方法
         *
         * return 去除重复item后的数组
         * */
        Array.prototype.unique = function () {
            this.sort(); //先排序
            var res = [this[0]];
            for (var i = 1; i < this.length; i++) {
                if (this[i] !== res[res.length - 1]) {
                    res.push(this[i]);
                }
            }
            return res;
        };


        $('#addTeacher').form({
            fields: {
                teacher_id: {
                    rules: [{
                        type: 'empty',
                        prompt: '请选择一个老师'
                    }]
                }
            },
            onSuccess: function () {
                vm.addTeacher();
                return false;
            }
        });

    }
}());
